
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
import undoable from 'redux-undo';

function sleep(milliseconds) {
  return new Promise(resolve => setTimeout(resolve, milliseconds));
}
export const fetchQs = createAsyncThunk('fetchQs', async () => {
  const response = await axios.get('/api/qs');
  await sleep(1000);
  return response.data;
});
export const fetchQAs = createAsyncThunk('fetchQAs', async () => {
  const response = await axios.get('/api/qas');
  await sleep(1000);
  return response.data;
});
export const fetchAnalysis = createAsyncThunk('analysis', async (data) => {
  const response = await axios.post('/api/analysis', data);
  return response.data;
});
export const fetchExplain0 = createAsyncThunk('explain0', async (an0) => {
  const response = await axios.post('/api/explain', { type: 0, an: an0 });
  return response.data;
});
export const fetchExplain1 = createAsyncThunk('explain1', async (an1) => {
  const response = await axios.post('/api/explain', { type: 1, an: an1 });
  return response.data;
});
export const fetchExplain2 = createAsyncThunk('explain2', async (an2) => {
  const response = await axios.post('/api/explain', { type: 2, an: an2 });
  return response.data;
});
export const fetchReq = createAsyncThunk('req', async (subjects) => {
  const response = await axios.get(`/api/req/${subjects}`);
  return response.data;
});
const questionsSlice = createSlice({
  name: 'questions',
  initialState: {
    qs: [],
    qas: undefined,
    currQ: undefined,
    analysis: undefined,
    explain0: undefined,
    explain1: undefined,
    explain2: undefined,
    req: undefined
  },
  reducers: {
    changeQ: (state, action) => {
      try {
        return {
          ...state,
          qas: undefined,
          analysis: undefined,
          explain0: undefined,
          explain1: undefined,
          explain2: undefined,
          req: undefined
        };
      } finally {
        window.history.pushState({ name: 'changeQ', timestamp: Date.now() }, null);
      }
    },
    setQs: (state, action) => {
      state.qs = action.payload;
      window.history.pushState({ name: 'setQs', timestamp: Date.now() }, null);
    },
    setCurrQ: (state, action) => {
      state.currQ = action.payload;
      window.history.pushState({ name: 'setCurrQ', timestamp: Date.now() }, null);
    },
    setQAs: (state, action) => {
      state.qas = action.payload;
      window.history.pushState({ name: 'setQAs', timestamp: Date.now() }, null);
    },
    setAnalysis: (state, action) => {
      state.analysis = action.payload;
      window.history.pushState({ name: 'setAnalysis', timestamp: Date.now() }, null);
    },
    setExplain0: (state, action) => {
      state.explain0 = action.payload;
      window.history.pushState({ name: 'setExplain0', timestamp: Date.now() }, null);
    },
    setExplain1: (state, action) => {
      state.explain1 = action.payload;
      window.history.pushState({ name: 'setExplain1', timestamp: Date.now() }, null);
    },
    setExplain2: (state, action) => {
      state.explain2 = action.payload;
      window.history.pushState({ name: 'setExplain2', timestamp: Date.now() }, null);
    }
  },
  extraReducers: {
    [fetchQs.fulfilled]: (state, action) => {
      if (!state.currQ) {
        return {
          ...state,
          qs: action.payload,
          currQ: action.payload[0]
        };
      } else {
        return {
          ...state,
          qs: action.payload
        }
      }
    },
    [fetchQAs.pending]: (state) => {
      return {
        ...state,
        qas: undefined,
        analysis: undefined,
        explain0: undefined,
        explain1: undefined,
        explain2: undefined,
        req: undefined
      };
    },
    [fetchQAs.fulfilled]: (state, action) => {
      state.qas = action.payload.map((qa, i) => {
        return { ...qa, show: 0 === i, answer: qa.type === 2 ? "如果按一天来算，我学习约10-11小时，进行体育锻炼1小时，休闲娱乐1-2小时，与家人和朋友互动1小时，以及进行其他日常活动如吃饭和洗澡大约1-2小时。" : undefined };
      });
    },
    [fetchAnalysis.pending]: (state) => {
      state.analysis = { status: 'pending' };
    },
    [fetchAnalysis.fulfilled]: (state, action) => {
      return {
        ...state,
        qas: state.qas.map((qa, i) => {
          if (qa.type === 2) {
            return { ...qa, answer_after_analysis: action.payload.an2_after_analysis };
          }
          return { ...qa };
        }),
        analysis: action.payload
      }
    },
    [fetchExplain0.pending]: (state) => {
      state.explain0 = { status: 'pending' };
    },
    [fetchExplain0.fulfilled]: (state, action) => {
      state.explain0 = action.payload;
    },
    [fetchExplain1.pending]: (state) => {
      state.explain1 = { status: 'pending' };
    },
    [fetchExplain1.fulfilled]: (state, action) => {
      state.explain1 = action.payload;
    },
    [fetchExplain2.pending]: (state) => {
      state.explain2 = { status: 'pending' };
    },
    [fetchExplain2.fulfilled]: (state, action) => {
      state.explain2 = action.payload;
    },
    [fetchReq.pending]: (state) => {
      state.req = { status: 'pending' };
    },
    [fetchReq.fulfilled]: (state, action) => {
      state.req = action.payload;
    }
  }
});

export const { setCurrQ, setQAs, changeQ, setExplain0, setExplain1, setExplain2 } = questionsSlice.actions;
export default undoable(questionsSlice.reducer);
